package logic.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Environment;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.Toast;

import com.NewActionHelp;
import com.shwread.android.ui.page.chat.adapter.ContactGroupAdapter;
import com.shwread.httpsdk.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import logic.constants.Const;


public class Utils {
    public static String filterName(String path) {
        String result = path;
        int index = path.lastIndexOf(File.separator);
        if (index != -1) {
            result = path.substring(index + 1);
        }
        index = result.lastIndexOf(".");
        if (index != -1) {
            result = result.substring(0, index);
        }
        return result;
    }

    /**
     * @param @param  index
     * @param @param  count
     * @param @param  minimum小数点后面的位数
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
     * @Title: getpercent
     * @Description: 计算百分比
     * @date 2012-2-17 上午10:07:24
     */
    public static String getPercent(long index, long count, int minimum) {
        if (count == 0) {
            return "0%";
        }
        DecimalFormat format = new DecimalFormat("###,##0");
        format.setMinimumFractionDigits(minimum);
        double per = ((double) index / count) * 100;
        return format.format(per);
    }

    public static String filterExt(String path) {
        String result = "";
        int index = path.lastIndexOf(".");
        if (index != -1) {
            result = path.substring(index + 1);
        }
        return result.toLowerCase();
    }

    //	public static SharedPreferences sharePreferences(Context context){
    //		SharedPreferences sp = context.getSharedPreferences(Const.SP_DATA_NAME, Context.MODE_PRIVATE);
    //		return sp;
    //	}
    //
    private static Toast sToast;

    public static void ToastShow(Context context, CharSequence charSequence) {
        if (sToast == null) sToast = Toast.makeText(context, charSequence, Toast.LENGTH_SHORT);
        else sToast.setText(charSequence);
        sToast.show();
    }

    public static void ToastShow(Context context, int id) {
        if (sToast == null) sToast = Toast.makeText(context, id, Toast.LENGTH_SHORT);
        else sToast.setText(id);
        sToast.show();
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    public static String getFormatDate(long time) {
        return sdf.format(new Date(time));
    }

    public static Date getStringtoDate(String strTime) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = sdf.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    private static SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");

    public static String getFormatTime(long time) {
        return sdf2.format(new Date(time));
    }

    static DecimalFormat df2 = new DecimalFormat("#0.00");
    static DecimalFormat df3 = new DecimalFormat("#0.0");

    public static String getMoneyFormat(double money) {
        return df2.format(money);
    }

    public static String getOneMoneyFormat(double money) {
        return df3.format(money);
    }

    public static String getPercent(long cur, long len) {
        float fPercent = (float) (cur * 1.0 / len);
        return df2.format(fPercent * 100);
    }

    /**
     * 计算文件的大小
     *
     * @param filesize
     * @return
     */
    public static String getFileSizeString(long filesize) {
        String sizeString = null;
        float size = 0;
        if (filesize < 1024) {
            //xx b
            size = filesize;
            sizeString = df2.format(size) + " B";
        } else if (filesize < 1024 * 1024) {
            //xx k
            size = (float) (filesize / 1024);
            sizeString = df2.format(size) + " KB";
        } else {
            //xx m
            size = (float) (filesize / (1024 * 1024));
            sizeString = df2.format(size) + " MB";
        }
        return sizeString;
    }

    public static String getString(String str, int maxsize) {
        if (str.length() > maxsize) {
            str = str.substring(0, maxsize);
        }
        return str;
    }

    public static String removeNameSpace(String ns_tag) {
        String[] ns__tag = ns_tag.split(":");
        return ns__tag[ns__tag.length - 1];
    }

    public static void showToast(Context mContext, int resId) {
        Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context mContext, String text) {
        Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断String为空
     *
     * @param string
     * @return
     */
    public static boolean isEmpty(String string) {
        return (string == null || "".equalsIgnoreCase(string.trim()) || "null".equals(string));
    }

    /**
     * 判断String不为空
     *
     * @param string
     * @return
     */
    public static boolean isNotEmpty(String string) {
        return string != null && string.trim().length() > 0;
    }

    public static final byte SCAN_TYPE_ALL = 0;
    public static final byte SCAN_TYPE_TXT = 1;
    public static final byte SCAN_TYPE_EPUB = 2;
    public static final byte SCAN_TYPE_PDF = 3;
    public static final byte SCAN_TYPE_OFFICE = 4;
    public static final byte SCAN_TYPE_OTHER = 5;

    public static final ArrayList<String> readFileTypeAll = new ArrayList<String>();
    public static final ArrayList<String> readFileTypeTxt = new ArrayList<String>();
    public static final ArrayList<String> readFileTypeEpub = new ArrayList<String>();
    public static final ArrayList<String> readFileTypePdf = new ArrayList<String>();
    public static final ArrayList<String> readFileTypeOffice = new ArrayList<String>();
    public static final ArrayList<String> readFileTypeOther = new ArrayList<String>();

    static {
        /** txt */
        readFileTypeTxt.add("txt");

        readFileTypeEpub.add("epub");

        readFileTypePdf.add("pdf");
        /** office */
        readFileTypeOffice.add("doc");
        //		readFileTypeOffice.add("xls");
        //		readFileTypeOffice.add("ppt");
        //		readFileTypeOffice.add("docx");
        //		readFileTypeOffice.add("xlsx");
        //		readFileTypeOffice.add("pptx");
        /** other */
        readFileTypeOther.add("rtf");
        readFileTypeOther.add("umd");

        //		readFileTypeOther.add("log");

        readFileTypeAll.addAll(readFileTypeTxt);
        readFileTypeAll.addAll(readFileTypeEpub);
        readFileTypeAll.addAll(readFileTypePdf);
        readFileTypeAll.addAll(readFileTypeOffice);
        readFileTypeAll.addAll(readFileTypeOther);
    }

    public static boolean isReaderFileType(File file) {
        if (file != null && file.exists() && file.isFile() && file.getPath().indexOf(".") != -1) {
            String path = file.getPath();
            String type = path.substring(path.lastIndexOf(".") + 1, path.length());
            return readFileTypeAll.contains(type);
        }
        return false;
    }

    public static byte getType(File file) {
        if (file != null && file.exists() && file.isFile() && file.getPath().indexOf(".") != -1) {
            String path = file.getPath();
            String type = path.substring(path.lastIndexOf(".") + 1, path.length());
            if (readFileTypeTxt.contains(type)) return SCAN_TYPE_TXT;
            else if (readFileTypeEpub.contains(type)) return SCAN_TYPE_EPUB;
            else if (readFileTypePdf.contains(type)) return SCAN_TYPE_PDF;
            else if (readFileTypeOffice.contains(type)) return SCAN_TYPE_OFFICE;
            else if (readFileTypeOther.contains(type)) return SCAN_TYPE_OTHER;
            else return SCAN_TYPE_ALL;
        }
        return SCAN_TYPE_ALL;
    }

    public static String getProcess(double paycount) {
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(paycount) + "%";
    }

    /**
     * bitmap转成byte[] 获得限制大小的图片JPEG数据 (用于头像)
     *
     * @param bitmap    图片
     * @param quality   起始jpeg图片质量
     * @param limitSize 限制的图片大小
     */
    public static byte[] getImageDataByLimitSize(Bitmap bitmap, int quality, int limitSize) {
        if (bitmap == null || limitSize <= 0) return null;

        if (quality <= 0) {
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, quality, baos);
        byte[] bytes = baos.toByteArray();

        if (bytes.length > limitSize) {
            bytes = null;
            bytes = getImageDataByLimitSize(bitmap, quality - 10, limitSize);
        }

        return bytes;
    }

    /**
     * 获取文件写入路径，无视错误
     *
     * @param fileName 文件全名
     * @return 返回路径，返回null则拒绝写入操作
     */
    public static String getWritePathIgnoreError(String fileName) {
        try {
            MultiCardFilePath path = MultiCard.getInstance().getWritePath(fileName);
            return path.getFilePath();
        } catch (LimitSpaceUnwriteException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据文件类型检查外置及内置存储卡是否有空间可写
     *
     * @param fileType 文件类型
     * @param type     检查范围,0表示所有,1表示只检查外置
     * @return
     */
    public static boolean isLimitSDCardSpaceForWrite(int fileType, int type) {
        return MultiCard.getInstance().checkSDCardSpace(fileType, type);
    }

    /**
     * 根据文件类型检查外置及内置存储卡是否超过预警空间
     *
     * @param fileType 文件类型
     * @param type     检查范围,0表示所有,1表示只检查外置
     * @return
     */
    public static boolean isLimitSDCardSpaceForWriteWarning(int fileType, int type) {
        return MultiCard.getInstance().islimitSpaceWarning(fileType, type);
    }

    /**
     * 判断存储卡空间(外置、内置存储卡是否有空间可写)
     *
     * @param context
     * @param fileType
     *            文件类型
     * @param type
     *            检查范围,0表示所有,1表示外置
     * @param bNeedTip
     *            是否要做出提示语
     * @return true表示无存储卡或无空间可写, false表示ok
     */
    //	public static boolean isSDCardSapceForWriteWithTip(Context context, int fileType, int type, boolean bNeedTip) {
    //		if (type == 0 && !Utils.isSDcardExist())
    //		{
    //			if (bNeedTip)
    //			{
    //				Utils.showToast(context, R.string.image_save_sdcard_deny);
    //			}
    //			return true;
    //		}
    //		else if (type == 1 && !Utils.isExternalSDCardExist())
    //		{
    //			if (bNeedTip)
    //			{
    //				Utils.showToast(context, R.string.image_save_sdcard_deny);
    //			}
    //			return true;
    //		}
    //
    //		if (!Utils.isLimitSDCardSpaceForWrite(fileType, type))
    //		{
    //			if (bNeedTip)
    //			{
    //				Utils.showToast(context, R.string.sdcard_not_enough);
    //			}
    //			return true;
    //		}
    //
    //		if (!Utils.isLimitSDCardSpaceForWriteWarning(fileType, type))
    //		{
    //			if (bNeedTip)
    //			{
    //				Utils.showToast(context, R.string.sdcard_not_enough_warning);
    //			}
    //		}
    //
    //		return false;
    //	}

    /**
     * 判断是否有SDCARD
     *
     * @return
     */
    public static boolean isSDcardExist() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 判断是否有外置存储卡
     *
     * @return
     */
    public static boolean isExternalSDCardExist() {
        return MultiCard.getInstance().isExternalSDCardExist();
    }

    /**
     * 根据时间格式得到时间段
     *
     * @return 刚刚,?分钟前,?小时前(24小时内) 昨天 时:分(24小时之前) 前天 时:分(48小时之前) 年-月-日
     * 时:分(72小时之前)
     */
    public static String getTimeByDuration(long time_l) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("MMdd");
            Date date = new Date(time_l);
            String date_s = formatter.format(new Date());
            String sDay = formatter.format(date);
            int index = (Integer.valueOf(sDay) - Integer.valueOf(date_s));
            if (index == 0) {
                formatter = new SimpleDateFormat("HH:mm");
                return formatter.format(date);
            } else if (index == -1) {
                return "昨天";
            } else if (index == -2) {
                return "前天";
            } else {
                formatter = new SimpleDateFormat("yyyy");
                String year = formatter.format(date);
                formatter = new SimpleDateFormat("MM");
                String yue = formatter.format(date);
                formatter = new SimpleDateFormat("dd");
                String ri = formatter.format(date);
                return Integer.parseInt(year) + "-" + Integer.parseInt(yue) + "-" + Integer.parseInt(ri);
            }
        } catch (Exception e) {
            return "";
        }
    }

    public static float getTextWidth(float textSize, String text) {
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        return paint.measureText(text);
    }

    public static final int getBitMapWidth(int res, Context context) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), res);
        return bitmap.getWidth();
    }

    public static final int getBitMapHeight(int res, Context context) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), res);
        return bitmap.getHeight();
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    public static Bitmap getRoundBitmap(Bitmap src) {
        float radius = src.getWidth() / 2f;
        Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);

        canvas.drawCircle(radius, radius, radius, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        canvas.drawBitmap(src, 0, 0, paint);

        return bitmap;
    }

    /**
     * 隐藏键盘
     *
     * @param mInputMethodManager
     * @param mView
     */
    public static void hideInputMethodManager(InputMethodManager mInputMethodManager, View mView) {
        if (mInputMethodManager != null && mView != null) {
            mInputMethodManager.hideSoftInputFromWindow(mView.getWindowToken(), 0);
        }
    }

    //显示键盘
    public static InputMethodManager showInputMethodManager(Context mContext) {
        final InputMethodManager mInputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mInputMethodManager.toggleSoftInput(InputType.TYPE_CLASS_PHONE, InputMethodManager.HIDE_NOT_ALWAYS);
        return mInputMethodManager;
    }

    /***
     * 判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查是否注册验证码
     *
     * @param num
     * @param msg
     * @return
     */
    public static String checkVerifySms(String msg) {
        String verify = null;

        String regex = "验证码:(.+)[(]本短信仅仅为了验证您的手机号码，您可以忽略[)]【天翼阅读】";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(msg.trim());
        if (matcher.find()) {
            verify = matcher.group(1).trim();
            //#debug
            base.tina.core.log.LogPrinter.d(null, "验证码:" + verify);

        }

        return verify;
    }

    public static String formetFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "B";
        } else if (fileSize < 1048576) {
            fileSizeString = df.format((double) fileSize / 1024) + "K";
        } else if (fileSize < 1073741824) {
            fileSizeString = df.format((double) fileSize / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /**
     * @param @param  url
     * @param @return 设定文件
     * @return String 返回类型
     * @throws
     * @Title: addUrlTimestamp
     * @Description: 在url后面增加时间戳骗过浏览器的缓存
     */
    public static String addUrlTimestamp(String url) {
        long timstamp = System.currentTimeMillis();

        if (url.indexOf("?") > 0) {
            url += "&t=" + timstamp;
        } else {
            url += "?t=" + timstamp;
        }
        return url;
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,6,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 判断一个字符串里面是否包含问号
     *
     * @param str
     * @return 包含为true 否则为false
     */
    public static boolean isHasQuestionMark(String str) {
        int i = str.indexOf("?");
        if (i == -1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 封装cid后的新的URL
     *
     * @param str1 为目标URL
     * @param str2 goodsId、str3 为 activityPrice 、
     * @return 拼装后新的URL
     */
    public static String appendString(String str1, String str2, String str3) {
        StringBuilder sb = new StringBuilder();
        String s1 = NewActionHelp.getAccount();
        String s2 = NewActionHelp.getAccountType();
        String s3 = NewActionHelp.getClientType();
        String s4 = NewActionHelp.getEnterpriseId();
        String s5 = String.valueOf(System.currentTimeMillis());
        String s6 = null;
        if (Utils.isNotEmpty(Const.login_key)) {
            s6 = Base64.base64Encode(s1 + s2 + s3 + s4 + s5, Const.login_key, "UTF-8");
        } else {
            s6 = Base64.base64Encode(s1 + s2 + s3 + s4 + s5, Const.SERVER_ENCRYPTKEY, "UTF-8");
        }

        if (isHasQuestionMark(str1)) {
            sb.append(str1);
        } else {
            sb.append(str1).append("?");
        }
        sb.append("&account=").append(s1).append("&accountType=").append(s2).append("&clientType=").append(s3).append("&enterpriseId=").append(s4).append("&timeStamp=").append(s5).append("&cid=").append(s6).append("&goodsId=").append(str2).append("&activityPrice=").append(str3);

        return sb.toString();
    }

    /**
     * 重新计算listview高度
     */
    public static void setListViewHeightBasedOnChildren(ListView listView, Adapter adapter) {
        if (adapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 重新计算ExpandableListView高度
     */
    public static void setExpandableListViewHeightBasedOnChildren(ExpandableListView listView, ContactGroupAdapter adapter) {
        if (adapter == null) {
            return;
        }

        int totalHeight = 0;
        int itemDividerHeightnum = 0;
        for (int i = 0; i < adapter.getGroupCount(); i++) {
            View listItem = adapter.getGroupView(i, true, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
            for (int j = 0; j < adapter.getChildrenCount(i); j++) {
                View listItemItem = adapter.getChildView(i, j, true, null, listView);
                listItemItem.measure(0, 0);
                totalHeight += listItemItem.getMeasuredHeight();
                itemDividerHeightnum++;
            }
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (itemDividerHeightnum + adapter.getGroupCount() - 1));
        listView.setLayoutParams(params);
    }
}
